package com.cg.design.graphicdesignpattern.strategy;

import java.util.Random;

/**
 * 表示“根据上一局的手势从概率上计算下一局的手势从之前的猜拳结果计算下一局出各种拳的概率”这一策略的类
 *
 * @program: LeetCode->ProbStrategy
 * @description: 表示“根据上一局的手势从概率上计算下一局的手势从之前的猜拳结果计算下一局出各种拳的概率”这一策略的类
 * @author: cg
 * @create: 2022-03-24 18:53
 **/
public class ProbStrategy implements Strategy {

    /**
     * 随机数生成器
     */
    private final Random random;

    /**
     * 上一局出的手势
     */
    private int prevHandValue = 0;

    /**
     * 这一局出的手势
     */
    private int currentHandValue = 0;

    /**
     * 矩阵表，用于根据过去的胜负来进行概论计算
     * history[上一局出的手势][这一局所出的手势]
     * 这个表达值越大，表示过去的胜率越高
     */
    private final int[][] history = {
            {1, 1, 1,},
            {1, 1, 1,},
            {1, 1, 1,},
    };

    public ProbStrategy(int seed) {
        random = new Random(seed);
    }

    @Override
    public Hand nextHand() {
        int bet = random.nextInt(getSum(currentHandValue));
        int handValue;
        if (bet < history[currentHandValue][0]) {
            handValue = 0;
        } else if (bet < history[currentHandValue][0] + history[currentHandValue][1]) {
            handValue = 1;
        } else {
            handValue = 2;
        }
        prevHandValue = currentHandValue;
        currentHandValue = handValue;
        return Hand.getHand(handValue);
    }

    private int getSum(int value) {
        int sum = 0;
        for (int i = 0; i < 3; i++) {
            sum += history[value][i];
        }
        return sum;
    }

    @Override
    public void study(boolean win) {
        if (win) {
            history[prevHandValue][currentHandValue]++;
        } else {
            history[prevHandValue][(currentHandValue + 1) % 3]++;
            history[prevHandValue][(currentHandValue + 2) % 3]++;
        }
    }
}
